package com.example.docking.service.impl;

import com.example.docking.dao.jindie.GenericDataItem;
import com.example.docking.dao.jindie.ResponseData;
import com.example.docking.dao.jindie.response.AuxInffoData;
import com.example.docking.service.AuxInfoService;
import com.example.docking.util.Constants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smecloud.apigw.model.ApiResult;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AuxInfoServiceImpl extends BaseServiceImpl implements AuxInfoService {
    @Override
    public String getTransTypeId(DataServiceImpl service, String typeName) throws Exception {
        Gson gson = new Gson();
        // 设置分页参数
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        String transid = "";

        ApiResult TransDataResult = service.SelectDataDetail(Constants.AUX_INFO, map, "");
        Type DataType = new TypeToken<ResponseData<GenericDataItem<AuxInffoData>>>() {
        }.getType();
        ResponseData<GenericDataItem<AuxInffoData>> responseTransData = gson.fromJson(TransDataResult.getBody(), DataType);
        GenericDataItem<AuxInffoData> genericDataItemTrans = responseTransData.getData();

        // 解析分页信息
        String count = genericDataItemTrans.getCount();
        int countNum = Integer.valueOf(count);
        int Pagesum = pageSize;
        int totalPage = genericDataItemTrans.getTotal_page();
        List<AuxInffoData> transData = genericDataItemTrans.getRows();

        List<AuxInffoData> allTransData = new ArrayList<>(transData);
        // 如果不是最后一页，继续获取下一页数据
        while (Pagesum < countNum) {
            page++;
            map.put("page", String.valueOf(page));
            TransDataResult = service.SelectDataDetail(Constants.AUX_INFO, map, "");
            responseTransData = gson.fromJson(TransDataResult.getBody(), DataType);
            genericDataItemTrans = responseTransData.getData();
            transData = genericDataItemTrans.getRows();
            allTransData.addAll(transData);
            Pagesum = pageSize * page;
        }

        boolean typeFound = false;
        for (AuxInffoData auxInffoData : allTransData) {
            if (auxInffoData.getName().equals(typeName)) {
                transid = auxInffoData.getId();
                typeFound = true;
                break;
            }
        }

        if (!typeFound) {
            // 这里可以根据业务需求添加未找到时的处理逻辑，比如返回默认值、抛出异常等
            // 目前简单返回空字符串
            transid = "";
        }

        return transid;
    }
}